package cn.edu.zust.lxy.wangke_backend.controller;

import cn.edu.zust.lxy.wangke_backend.common.Result;
import cn.edu.zust.lxy.wangke_backend.mapper.BookMapper;
import cn.edu.zust.lxy.wangke_backend.mapper.UserMapper;
import cn.edu.zust.lxy.wangke_backend.model.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author keboom
 * @date 2021/6/14 20:22
 */
@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/list")
    public Result<List<Book>> list() {
        List<Book> bookList = bookMapper.getBookList();
        return new Result<List<Book>>(200, "查询成功", bookList);
    }

    @PostMapping("/appointment")
    public Result appointment(String user_name, String book_title) {
        Integer userId = userMapper.getIdByName(user_name);
        Integer bookId = bookMapper.getIdByBookTitle(book_title);
        userMapper.appointment(bookId, userId);
        bookMapper.setAppointmented(bookId);
        return new Result(201, "预约成功", null);
    }

    @PostMapping("/borrow")
    public Result borrow(String user_name, String book_title) {
        Integer userId = userMapper.getIdByName(user_name);
        Integer bookId = bookMapper.getIdByBookTitle(book_title);
        userMapper.borrow(bookId, userId);
        bookMapper.setBorrowed(bookId);
        return new Result(201, "借阅成功", null);
    }

    @GetMapping("/queryBooks")
    public Result queryBooks(String book_title) {
        List<Book> books = bookMapper.queryBooks("%" + book_title + "%");
        return new Result(200, "查询图书成功", books);
    }
}
